package cn.stylefeng.guns.modular.cb.controller;

import cn.stylefeng.guns.base.auth.context.LoginContextHolder;
import cn.stylefeng.guns.base.auth.model.LoginUser;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.modular.cb.entity.CbMessages;
import cn.stylefeng.guns.modular.cb.model.params.CbCustomerStaffParam;
import cn.stylefeng.guns.modular.cb.model.params.CbMessageTemplateParam;
import cn.stylefeng.guns.modular.cb.model.params.CbMessagesParam;
import cn.stylefeng.guns.modular.cb.model.params.CbWxTemplateParam;
import cn.stylefeng.guns.modular.cb.model.result.CbCustomerStaffResult;
import cn.stylefeng.guns.modular.cb.model.result.CbMessageTemplateResult;
import cn.stylefeng.guns.modular.cb.model.result.CbMessagesResult;
import cn.stylefeng.guns.modular.cb.model.result.CbWxTemplateResult;
import cn.stylefeng.guns.modular.cb.service.CbCustomerStaffService;
import cn.stylefeng.guns.modular.cb.service.CbMessageTemplateService;
import cn.stylefeng.guns.modular.cb.service.CbMessagesService;
import cn.stylefeng.guns.modular.cb.service.CbWxTemplateService;
import cn.stylefeng.guns.sys.modular.system.entity.User;
import cn.stylefeng.guns.sys.modular.system.service.UserService;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.kernel.model.response.ResponseData;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


/**
 * 控制器
 *
 * @author ss
 * @Date 2021-01-19 19:43:23
 */
@Controller
@RequestMapping("/cbMessages")
public class CbMessagesController extends BaseController {

    private static Logger logger = LoggerFactory.getLogger(CbMessagesController.class);

    private String PREFIX = "/cb/cbMessages";

    @Autowired
    private CbMessagesService cbMessagesService;

    @Autowired
    private CbCustomerStaffService staffService;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private CbWxTemplateService wxTemplateService;

    @Autowired
    private UserService userService;

    @Value("${wx.appid}")
    private String appid;
    @Value("${wx.secret}")
    private String secret;

    @Value("${wx.open.appid}")
    private String openAppid;
    @Value("${wx.open.secret}")
    private String openSecret;

    private static Map<String, String> tokenMap = new ConcurrentHashMap<>();

    /**
     * 跳转到主页面
     *
     * @author ss
     * @Date 2021-01-19
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "/cbMessages.html";
    }

    /**
     * 新增页面
     *
     * @author ss
     * @Date 2021-01-19
     */
    @RequestMapping("/add")
    public String add() {
        return PREFIX + "/cbMessages_add.html";
    }

    /**
     * 编辑页面
     *
     * @author ss
     * @Date 2021-01-19
     */
    @RequestMapping("/edit")
    public String edit() {
        return PREFIX + "/cbMessages_edit.html";
    }

    /**
     * 新增接口
     *
     * @author ss
     * @Date 2021-01-19
     */
    @RequestMapping("/addItem")
    @ResponseBody
    public ResponseData addItem(CbMessagesParam cbMessagesParam) {
        //交换联系方式 一天一次
//        if (cbMessagesParam.getType() == 3) {
//            List<CbMessagesResult> list = this.cbMessagesService.getMessageByNow(cbMessagesParam);
//            if (list != null && list.size() > 0) {
//                return ResponseData.error(550, "交换联系方式每天只能申请一次");
//            }
//        }
        cbMessagesParam.setStatus(0L);
        cbMessagesParam.setEventid(0L);
        this.cbMessagesService.add(cbMessagesParam);
        return ResponseData.success();
    }

    /**
     * 简历投递邀请
     *
     * @author ss
     * @Date 2021-01-19
     */
    @RequestMapping("/invitation")
    @ResponseBody
    public ResponseData invitation(CbMessagesParam cbMessagesParam) {
        try {
            cbMessagesParam.setType(6L);
            cbMessagesParam.setStatus(0L);
            cbMessagesParam.setEventid(0L);

            //获取发消息人id
            LoginUser user = LoginContextHolder.getContext().getUser();
            CbCustomerStaffParam staffParam = new CbCustomerStaffParam();
            staffParam.setCreateUser(user.getId());
            CbCustomerStaffResult staffResult = staffService.getStaffDetail(staffParam);
            if (staffResult!=null){
                cbMessagesParam.setSendUserid(staffResult.getId());//发消息人
            }


//            if (cbMessagesParam.getType() == 6) {///邀请投递，一天一次
//                List<CbMessagesResult> list = this.cbMessagesService.getMessageByNow(cbMessagesParam);
//                if (list != null && list.size() > 0) {
//                    return ResponseData.error(550, "今日已邀请，明天才能再次邀请投递");
//                }
//            }

            //消息内容
//            CbMessageTemplateParam mtParam = new CbMessageTemplateParam();
//            mtParam.setType("MT_YQTD");//邀请投递
//            CbMessageTemplateResult mtResult = messageTemplateService.findBySpec(mtParam);
//            String message = "邀请投递职位可以内推";
//            if (mtResult!=null && mtResult.getId()!=null){
//                message = mtResult.getDescription().replace("name", staffResult.getName());
//            }
//            cbMessagesParam.setMessage(message);
            this.cbMessagesService.add(cbMessagesParam);
        } catch (Exception e) {
            logger.error("简历投递邀请错误");
            logger.error("invitation message error: ", e);
        }
        return ResponseData.success();
    }

    /**
     * 编辑接口
     *
     * @author ss
     * @Date 2021-01-19
     */
    @RequestMapping("/editItem")
    @ResponseBody
    public ResponseData editItem(CbMessagesParam cbMessagesParam) {
        this.cbMessagesService.update(cbMessagesParam);
        return ResponseData.success();
    }

    /**
     * 删除接口
     *
     * @author ss
     * @Date 2021-01-19
     */
    @RequestMapping("/delete")
    @ResponseBody
    public ResponseData delete(CbMessagesParam cbMessagesParam) {
        this.cbMessagesService.delete(cbMessagesParam);
        return ResponseData.success();
    }

    /**
     * 查看详情接口
     *
     * @author ss
     * @Date 2021-01-19
     */
    @RequestMapping("/detail")
    @ResponseBody
    public ResponseData detail(CbMessagesParam cbMessagesParam) {
        CbMessages detail = this.cbMessagesService.getById(cbMessagesParam.getId());
        return ResponseData.success(detail);
    }

    /**
     * 新增接口
     *
     * @author ss
     * @Date 2021-01-19
     */
    @RequestMapping("/editStaus")
    @ResponseBody
    public ResponseData editStaus(CbMessagesParam cbMessagesParam) {
        this.cbMessagesService.update(cbMessagesParam);
        return ResponseData.success();
    }

    /**
     * 新增接口
     *
     * @author ss
     * @Date 2021-01-19
     */
    @RequestMapping("/getinformation")
    @ResponseBody
    public ResponseData getinformation(CbMessagesParam cbMessagesParam) {
        try {
            cbMessagesParam.setType(3L);
            cbMessagesParam.setMessage("您收到一条请求交换联系方式的信息");
            cbMessagesParam.setStatus(0L);
            cbMessagesService.add(cbMessagesParam);
        } catch (Exception e) {
            logger.error("getinformation error: ", e);
        }
        return ResponseData.success();
    }

    /**
     * 查询列表
     *
     * @author ss
     * @Date 2021-01-19
     */
    @ResponseBody
    @RequestMapping("/list")
    public LayuiPageInfo list(CbMessagesParam cbMessagesParam) {
        return this.cbMessagesService.getSysMessageList(cbMessagesParam);
    }


    /**
     * 企业获取简历消息
     *
     * @author ss
     * @Date 2021-01-19
     */
    @ResponseBody
    @RequestMapping("/getResumeMessageList")
    public LayuiPageInfo getResumeMessageList(CbMessagesParam cbMessagesParam) {
        LayuiPageInfo layuiPageInfo = this.cbMessagesService.getResumeMessageList(cbMessagesParam);
        List<CbMessagesResult> list = layuiPageInfo.getData();
        updateMessageStatus(list);//更新消息状态
        return layuiPageInfo;
    }

    /**
     * 员工获取投递消息
     *
     * @author ss
     * @Date 2021-01-19
     */
    @ResponseBody
    @RequestMapping("/getStaffResumeMessageList")
    public LayuiPageInfo getStaffResumeMessageList(CbMessagesParam cbMessagesParam) {
        LayuiPageInfo layuiPageInfo = this.cbMessagesService.getStaffResumeMessageList(cbMessagesParam);
        List<CbMessagesResult> list = layuiPageInfo.getData();
        updateMessageStatus(list);//更新消息状态
        return layuiPageInfo;
    }

    /**
     * 企业查看员工消息
     *
     * @author ss
     * @Date 2021-01-19
     */
    @ResponseBody
    @RequestMapping("/getOtherMessageList")
    public LayuiPageInfo getOtherMessageList(CbMessagesParam cbMessagesParam) {
        LayuiPageInfo layuiPageInfo = this.cbMessagesService.getOtherMessageList(cbMessagesParam);
        List<CbMessagesResult> list = layuiPageInfo.getData();
        updateMessageStatus(list);//更新消息状态
        return layuiPageInfo;
    }

    /**
     * 学生获取其他消息
     *
     * @author ss
     * @Date 2021-01-19
     */
    @ResponseBody
    @RequestMapping("/getStudentOtherMessageList")
    public LayuiPageInfo getStudentOtherMessageList(CbMessagesParam cbMessagesParam) {
        LayuiPageInfo layuiPageInfo = this.cbMessagesService.getStudentOtherMessageList(cbMessagesParam);
        List<CbMessagesResult> list = layuiPageInfo.getData();
        updateMessageStatus(list);//更新消息状态
        return layuiPageInfo;
    }

    /**
     * 员工获取其他消息
     *
     * @author ss
     * @Date 2021-01-19
     */
    @ResponseBody
    @RequestMapping("/getStaffOtherMessageList")
    public LayuiPageInfo getStaffOtherMessageList(CbMessagesParam cbMessagesParam) {
        LayuiPageInfo layuiPageInfo = this.cbMessagesService.getStaffOtherMessageList(cbMessagesParam);
        List<CbMessagesResult> list = layuiPageInfo.getData();
        updateMessageStatus(list);//更新消息状态
        return layuiPageInfo;
    }

    /**
     * 查询学生消息列表，获取被邀请的投递信息
     *
     * @author ss
     * @Date 2021-01-19
     */
    @ResponseBody
    @RequestMapping("/getInvitationMessageList")
    public LayuiPageInfo getInvitationMessageList(CbMessagesParam cbMessagesParam) {
        LayuiPageInfo layuiPageInfo = this.cbMessagesService.getInvitationMessageList(cbMessagesParam);
        List<CbMessagesResult> list = layuiPageInfo.getData();
        updateMessageStatus(list);//更新消息状态
        return layuiPageInfo;
    }

    //查询系统消息
    @ResponseBody
    @RequestMapping("/getStuSysMessageList")
    public LayuiPageInfo getStuSysMessageList(CbMessagesParam cbMessagesParam) {
        cbMessagesParam.setEventid(3L);
        LayuiPageInfo layuiPageInfo = this.cbMessagesService.getSysMessageList(cbMessagesParam);
        List<CbMessagesResult> list = layuiPageInfo.getData();
        updateMessageStatus(list);//更新消息状态
        return layuiPageInfo;
    }

    //查询系统消息
    @ResponseBody
    @RequestMapping("/getStaffSysMessageList")
    public LayuiPageInfo getStaffSysMessageList(CbMessagesParam cbMessagesParam) {
        cbMessagesParam.setEventid(2L);
        LayuiPageInfo layuiPageInfo = this.cbMessagesService.getSysMessageList(cbMessagesParam);
        List<CbMessagesResult> list = layuiPageInfo.getData();
        updateMessageStatus(list);//更新消息状态
        return layuiPageInfo;
    }

    //查询系统消息

    @ResponseBody
    @RequestMapping("/getSysMessageList")
    public LayuiPageInfo getSysMessageList(CbMessagesParam cbMessagesParam) {
        cbMessagesParam.setEventid(1L);
        LayuiPageInfo layuiPageInfo = this.cbMessagesService.getSysMessageList(cbMessagesParam);
        List<CbMessagesResult> list = layuiPageInfo.getData();
        updateMessageStatus(list);//更新消息状态
        return layuiPageInfo;
    }

    //    员工申请操作
    @RequestMapping("/handleEmployeeApplication")
    @ResponseBody
    public ResponseData handleEmployeeApplication(CbMessagesParam cbMessagesParam) {
        this.cbMessagesService.handleEmployeeApplication(cbMessagesParam);
        return ResponseData.success();
    }

    //    员工申请操作
    @RequestMapping("/StaffSignOut")
    @ResponseBody
    public ResponseData StaffSignOut(CbMessagesParam cbMessagesParam) {
        //如果申请统一则新增一个消息
        try {
            cbMessagesParam.setType(7L);
            cbMessagesParam.setMessage("退出公司");
            cbMessagesParam.setStatus(0L);
            cbMessagesService.add(cbMessagesParam);
        } catch (Exception e) {
            logger.error("staff sign out error: ", e);
        }
        return ResponseData.success();
    }

    //申请联系方式操作

    /**
     * 处理申请获取联系方式
     *
     * @author ss
     * @Date 2021-01-19
     */
    @RequestMapping("/handleSwapInformation")
    @ResponseBody
    public ResponseData handleSwapInformation(CbMessagesParam cbMessagesParam) {
        this.cbMessagesService.handleSwapInformation(cbMessagesParam);
        return ResponseData.success();
    }

    /**
     * 消息类型数量
     *
     * @param cbMessagesParam
     * @return
     */
    @ResponseBody
    @RequestMapping("/get_count_type")
    public ResponseData getCountByType(CbMessagesParam cbMessagesParam) {
        Integer count = cbMessagesService.getCountByType(cbMessagesParam);
        return ResponseData.success(count);
    }

    /**
     * 系统消息
     *
     * @param cbMessagesParam
     * @return
     */
    @ResponseBody
    @RequestMapping("/send_sys_msg")
    public ResponseData sendSysMsg(CbMessagesParam cbMessagesParam) {
        cbMessagesService.sendSysMessage(cbMessagesParam);
        return ResponseData.success();
    }

    /**
     * 更新消息状态
     */
    private void updateMessageStatus(List<CbMessagesResult> list) {
        //0未读 1已读
        try {
            for (CbMessagesResult result : list) {
                if (result.getStatus()!=null && result.getStatus() == 0) {
                    CbMessagesParam param = new CbMessagesParam();
                    param.setId(result.getId());
                    param.setStatus(1L);
                    this.cbMessagesService.update(param);
                }
            }
        } catch (Exception e) {
            logger.error("update message status error: ", e);
        }
    }

    /**
     * 获取公众号token
     */
    private void setToken() {
        String tokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret;
        String jsonData = restTemplate.getForObject(tokenUrl, String.class);
        /*{"access_token":"43_b5GNGu0Fg9a0qnvNhOAtuuhmjBvScAzQjhPCOjoFh6dkxFmP0LDQ9stqPXza4cR5_9_UN6CNoSWJDMAXKMDidblHijkPXMtmJBUACpqjlqN4Zs6GR1OxHCrIvaD7-zKCUYTc_7JpDWth2v8eCIMeABAGMQ","expires_in":7200}*/
        JSONObject data = JSON.parseObject(jsonData);
        Long expiresIn = data.getLong("expires_in") * 1000;//有效期
        String token = data.getString("access_token");
        expiresIn += System.currentTimeMillis();//当前时间+有效时长
        tokenMap.put("token", token);
        tokenMap.put("expiresIn", expiresIn.toString());
    }

    /**
     * 发送模板消息
     *
     * @return
     */
    @RequestMapping("/sendTemplat")
    @ResponseBody
    public ResponseData sendTemplat(CbWxTemplateParam wxTemplateParam) {
        try {
            //获取公众号模板
            CbWxTemplateResult wxTemplateResult = wxTemplateService.findBySpec(wxTemplateParam);

//            wxTemplateParam.setFirst("你有一条新的消息");
//            wxTemplateParam.setKeyword1("材必小程序");
//            wxTemplateParam.setKeyword2(String.valueOf(LocalDate.now()));
//            wxTemplateParam.setKeyword3("查收");
//            wxTemplateParam.setRemark("备注：xxx");
//            logger.info("wxTemplateParam: {}", wxTemplateParam.toString());

            //获取token
            String expiresIn = tokenMap.get("expiresIn");
            String token = tokenMap.get("token");
            if (StringUtils.isEmpty(expiresIn) || expiresIn.compareTo(String.valueOf(System.currentTimeMillis() + 5 * 1000)) <= 0) {//提前5秒过期
                setToken();
                token = tokenMap.get("token");
            }

            //模板发送接口
            String sendUrl = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/uniform_send?" +
                    "access_token=" + token;

            //获取目标openId
            User user = userService.getById(wxTemplateParam.getUserId());

            //模板一
            JSONObject template1 = new JSONObject();
            template1.put("touser", user.getOpenId());//用户openId，可以是小程序的也可以是公众号的

            JSONObject mpTemplateMsg = new JSONObject();
            mpTemplateMsg.put("appid", openAppid);//公众号appid
            String templateId = wxTemplateResult.getTemplateId();//模板id

            //根据模板类型获取模板id
            //模板类型 1：关注 2：交换联系方式 3：邀请投递 4：简历投递
            switch (wxTemplateParam.getType()) {
                case 1:
                case 2:
                case 4:
                    break;
                case 3:
                    break;
                default:
                    break;
            }
            mpTemplateMsg.put("template_id", templateId);//公众号模板Id
            mpTemplateMsg.put("url", wxTemplateParam.getUrl());//

            JSONObject miniprogram = new JSONObject();
            miniprogram.put("appid", appid);//小程序appId
            miniprogram.put("pagepath", wxTemplateParam.getPagepath());//小程序页面
            mpTemplateMsg.put("miniprogram", miniprogram);

            JSONObject data = new JSONObject();
            JSONObject first = new JSONObject();
            String firstMsg = wxTemplateResult.getFirst();
            if (StringUtils.isEmpty(firstMsg)) {
                firstMsg = "";
            }
            first.put("value", firstMsg);
            data.put("first", first);

            JSONObject keyword1 = new JSONObject();
            String keyword1Msg = wxTemplateResult.getKeyword1();
            if (StringUtils.isEmpty(keyword1Msg)) {
                keyword1Msg = "";
            }
            keyword1.put("value", keyword1Msg);
            data.put("keyword1", keyword1);

            JSONObject keyword2 = new JSONObject();
            String keyword2Msg = wxTemplateResult.getKeyword2();
            if (StringUtils.isEmpty(keyword2Msg)) {
                keyword2Msg = "";
            }
            keyword2.put("value", keyword2Msg);
            data.put("keyword2", keyword2);

            JSONObject keyword3 = new JSONObject();
            String keyword3Msg = wxTemplateResult.getKeyword3();
            if (StringUtils.isEmpty(keyword3Msg)) {
                keyword3Msg = "";
            }
            keyword3.put("value", keyword3Msg);
            data.put("keyword3", keyword3);

            JSONObject remark = new JSONObject();
            String remarkMsg = wxTemplateResult.getRemark();
            if (StringUtils.isEmpty(remarkMsg)) {
                remarkMsg = "";
            }
            remark.put("value", remarkMsg);
            data.put("remark", remark);

            mpTemplateMsg.put("data", data);

            template1.put("mp_template_msg", mpTemplateMsg);
            JSONObject result = restTemplate.postForObject(sendUrl, template1, JSONObject.class);
            logger.info("发送模板消息返回值： {}", result);
        } catch (Exception e) {
            logger.error("send template message error: ", e);
        }
        return ResponseData.success();
    }
}


